package ddz.utils;

/**
 * 翻页辅助类
 *
 * @author zkpursuit
 */
public class Page {

    /**
     * 每页的开始索引，从0开始
     */
    private int start;
    /**
     * 每页数据数量
     */
    private int num;
    /**
     * 总数据量
     */
    private int totals;
    /**
     * 页号索引，从1开始
     */
    private int pageIndex;
    /**
     * 总页数
     */
    private int pageTotals;

    /**
     * 构造方法
     *
     * @param num       每页数量
     * @param pageIndex 页索引，从1开始
     */
    public Page(int num, int pageIndex) {
        this.num = num;
        this.pageIndex = pageIndex;
    }

    public int getStart() {
        return start;
    }

    public int getNum() {
        return num;
    }

    public int getTotals() {
        return totals;
    }

    /**
     * 设置数据总数量
     *
     * @param totals 数据总量
     */
    public void setTotals(int totals) {
        this.totals = totals;
        this.recalc();
    }

    public int getPageIndex() {
        return pageIndex;
    }

    public int getPageTotals() {
        return pageTotals;
    }

    /**
     * 重新计算
     */
    protected void recalc() {
        if (this.num <= 0) {
            this.num = totals;
            this.pageTotals = 1;
            this.pageIndex = 1;
            this.start = 0;
        } else {
            this.pageTotals = (int) Math.ceil((float) this.totals / this.num);
            if (this.pageIndex > this.pageTotals) {
                this.pageIndex = this.pageTotals;
            }
            this.start = (this.pageIndex - 1) * this.num; //由于limit从0开始计算，故而需要减1
            int remaing = this.totals - this.pageIndex * this.num;
            if (remaing < 0) {
                this.num = this.num - Math.abs(remaing);
            }
        }
    }

}
